<template>
  <div class="login-page">
    <div class="login-box">
      <div class="head-box">假接口</div>
      <div v-if="state.isShow">
        <el-form
          ref="loginFormRef"
          :model="loginForm"
          :rules="loginRules"
          class="core-box"
          auto-complete="on"
          label-position="left"
        >
          <div class="title-container">
            <h3 class="title" style="margin-bottom: 50px">欢迎登录</h3>
          </div>

          <el-form-item prop="sjh">
            <el-input
              :prefix-icon="Iphone"
              v-model="loginForm.sjh"
              placeholder="请输入手机号"
              name="sjh"
              type="text"
              tabindex="1"
              auto-complete="on"
              clearable
            />
          </el-form-item>

          <el-form-item prop="mm">
            <el-input
              :prefix-icon="Lock"
              v-model="loginForm.mm"
              type="text"
              placeholder="请输入密码，字母、数字组合至少8位"
              name="mm"
              tabindex="2"
              auto-complete="on"
              clearable
              show-password
              @keyup.enter="handleLogin"
            />
          </el-form-item>

          <div class="wjmm" @click="handleForgetPassword">忘记密码?</div>
          <div class="anniu" @click.prevent="handleLogin">登录</div>
          <div class="other" @click="goReg">没有账号？去注册</div>
          <div class="xieyi" style="margin-top: 120px">
            <span>登录即代表同意</span>
            <span class="gen" @click="goAgreement">《用户隐私协议》</span>
          </div>
        </el-form>
      </div>

      <div v-else>
        <el-form
          ref="forgotPasswordFormRef"
          :model="forgotPasswordForm"
          :rules="forgotPasswordRules"
          class="core-box"
          auto-complete="on"
          label-position="left"
        >
          <div class="title-container">
            <h3 class="title" style="margin-bottom: 30px">忘记密码</h3>
          </div>
          <el-form-item prop="sjh">
            <el-input
              :prefix-icon="Iphone"
              v-model="forgotPasswordForm.sjh"
              placeholder="请输入手机号"
              name="sjh"
              type="text"
              tabindex="1"
              auto-complete="on"
              clearable
            />
          </el-form-item>
          <el-form-item prop="code">
            <el-input
              v-model="forgotPasswordForm.code"
              placeholder="请输入图片验证码"
              name="code"
              style="width: 70%"
              clearable
            >
              <template #prefix>
                <img :src="iconPic.yzm" />
              </template>
            </el-input>
            <div class="captcha">
              <img v-if="codeImgUrl" :src="codeImgUrl" @click="handleCaptchaGenerate" />
            </div>
          </el-form-item>
          <el-form-item prop="verification_code">
            <el-input
              :prefix-icon="ChatDotSquare"
              v-model="forgotPasswordForm.verification_code"
              name="verification_code"
              maxlength="4"
              placeholder="请输入短信验证码"
            >
              <template #suffix>
                <div>
                  <div v-if="counter > 0" class="daojishi">{{ countdownText }}</div>
                  <div v-else @click="sendSmsCode" class="huoqu">获取验证码</div>
                </div>
              </template>
            </el-input>
          </el-form-item>
          <el-form-item prop="mm">
            <el-input
              :prefix-icon="Lock"
              v-model="forgotPasswordForm.mm"
              type="text"
              placeholder="请输入新密码"
              name="mm"
              tabindex="2"
              clearable
              show-password
            />
          </el-form-item>
          <el-form-item prop="xmm">
            <el-input
              :prefix-icon="Lock"
              v-model="forgotPasswordForm.xmm"
              type="text"
              placeholder="请再次确认密码"
              name="xmm"
              tabindex="2"
              clearable
              show-password
            />
          </el-form-item>
          <div style="display: flex; justify-content: space-between">
            <div class="anniu" @click.prevent="handleConfirm" style="width: 150px">确认</div>
            <div class="anniu" @click.prevent="handleReturn" style="width: 150px">返回登录</div>
          </div>
          <div class="xieyi" style="margin-top: 20px">
            <span>登录即代表同意</span>
            <span class="gen" @click="goAgreement">《用户隐私协议》</span>
          </div>
        </el-form>
      </div>
    </div>
    <div v-if="showCopyright" class="copyright">
      <p>有限公司提供技术支持</p>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, reactive, ref, toRefs } from 'vue';
import { ElForm, ElInput, ElMessage } from 'element-plus';
import { Iphone, Lock, ChatDotSquare } from '@element-plus/icons-vue';
import router from '@/router';
import useStore from '@/store';
import { getCaptcha, sendCode, forgotPassword } from '@/api/logreg/index';
import { LoginForm, ForgotPasswordForm } from '@/api/logreg/types';

const { user } = useStore();

const loginFormRef = ref(ElForm);
const forgotPasswordFormRef = ref(ElForm);

const state = reactive({
  isShow: true,
  loginForm: {
    sjh: '20233302324',
    mm: '123456abc'
  } as LoginForm,
  loginRules: {
    sjh: [
      { required: true, message: '手机号不能为空', trigger: 'blur' },
      { min: 11, max: 11, message: '请输入11位的手机号', trigger: 'blur' }
    ],
    mm: [
      { required: true, message: '密码不能为空', trigger: 'blur' },
      {
        pattern: /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,20}$/,
        message: '密码须为8~20位数字和字母组合',
        trigger: 'blur'
      }
    ]
  },
  throttle: true,

  forgotPasswordForm: {} as ForgotPasswordForm,
  forgotPasswordRules: {
    sjh: [
      { required: true, message: '手机号不能为空', trigger: 'blur' },
      { min: 11, max: 11, message: '请输入11位的手机号', trigger: 'blur' }
    ],
    verification_code: [{ required: true, message: '短信验证码不能为空', trigger: 'blur' }],
    mm: [
      { required: true, message: '密码不能为空', trigger: 'blur' },
      {
        pattern: /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,20}$/,
        message: '密码须为8~20位数字和字母组合',
        trigger: 'blur'
      }
    ],
    xmm: [
      { required: true, message: '密码不能为空', trigger: 'blur' },
      {
        pattern: /^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{8,20}$/,
        message: '密码须为8~20位数字和字母组合',
        trigger: 'blur'
      }
    ]
  },
  codeImgUrl: '', // 图片验证码
  iconPic: {
    yzm: new URL('/src/assets/img/login/yzm.png', import.meta.url).href
  },
  counter: 0, // 计数器
  countdownText: '', // 倒计时文本
  timer: '' as any, // 计时器对象
  clientHeight: document.documentElement.clientHeight,
  showCopyright: true
});

const {
  loginForm,
  loginRules,
  forgotPasswordForm,
  forgotPasswordRules,
  codeImgUrl,
  iconPic,
  counter,
  countdownText,
  showCopyright
} = toRefs(state);

// 整个模板假接口不能使用
function handleLogin() {
  localStorage.setItem('token', JSON.stringify('Bearer abc'));
  router.push('/');
}

// 登录处理
function handleLogin2() {
  loginFormRef.value.validate((valid: boolean) => {
    if (valid) {
      if (state.throttle) {
        state.throttle = false;
        user
          .login(state.loginForm)
          .then(() => {
            router.push('/');
            state.throttle = true;
          })
          .catch(() => {
            state.throttle = true;
          });
      }
    } else {
      return false;
    }
  });
}

// 跳转到注册页
function goReg() {
  router.push('/register');
}
// 跳转到用户隐私协议
function goAgreement() {
  console.log('跳转到用户隐私协议');
}

// 处理忘记密码
function handleForgetPassword() {
  handleCaptchaGenerate();
  state.isShow = false;
  state.forgotPasswordForm = {
    sjh: '',
    verification_code: '',
    verification_key: '',
    mm: '',
    xmm: '',
    code: '', // 图片验证码
    key: '' // 验证码图片key
  } as ForgotPasswordForm;
}
// 获取图片验证码
function handleCaptchaGenerate() {
  getCaptcha().then(({ data }) => {
    const { img, key } = data;
    state.codeImgUrl = img;
    state.forgotPasswordForm.key = key;
  });
}
// 获取短信验证码
function sendSmsCode() {
  forgotPasswordFormRef.value.validateField(['sjh', 'code'], (valid: boolean) => {
    if (valid) {
      let { sjh, code, key } = state.forgotPasswordForm;
      let datas = { sjh, code, key } as any;
      sendCode(datas)
        .then((res: any) => {
          countdown();
          state.forgotPasswordForm.verification_key = res.data.key;
        })
        .catch(() => {
          handleCaptchaGenerate();
        });
    }
  });
}
// 倒计时
function countdown() {
  state.counter = 30;
  state.countdownText = state.counter + 's';
  state.timer = setInterval(() => {
    state.counter--;
    state.countdownText = state.counter + 's';
    if (state.counter < 0) {
      clearInterval(state.timer);
    }
  }, 1000);
}
// 确认并登录
function handleConfirm() {
  if (state.forgotPasswordForm.mm == state.forgotPasswordForm.xmm) {
    let { sjh, mm, verification_code, verification_key } = state.forgotPasswordForm;
    let datas = {
      sjh,
      mm,
      verification_code,
      verification_key
    } as ForgotPasswordForm;
    forgotPassword(datas).then((res: any) => {
      ElMessage.success(res.msg);
      state.isShow = true;
    });
  } else {
    ElMessage.error('确认密码不匹配，请重新输入');
  }
}
// 返回登录
function handleReturn() {
  state.isShow = true;
}
onMounted(() => {
  window.onresize = () => {
    if (state.clientHeight > document.documentElement.clientHeight) {
      state.showCopyright = false;
    } else {
      state.showCopyright = true;
    }
  };
});
</script>

<style lang="scss" scoped>
.login-page {
  background: url('../../assets/img/login/bg.png') no-repeat;
  height: 100vh;
  width: 100%;
  overflow: hidden;
  background-size: cover;
}

.login-box {
  margin-left: 60%;
  height: 620px;
  width: 512px;
  background-color: #fff;
  overflow: hidden;
  @media (max-width: 2560px) {
    margin-top: 10%;
  }
  @media (max-width: 1920px) {
    margin-top: 5%;
  }

  .head-box {
    text-align: center;
    margin-top: 50px;
    font-size: 28px;
    font-family: PingFang SC;
    font-weight: bold;
    color: #4a7bfe;
  }

  .core-box {
    position: relative;
    width: 320px;
    max-width: 100%;
    padding: 60px 35px 0;
    margin: 0 auto;
    overflow: hidden;

    .title-container {
      position: relative;

      .title {
        font-size: 20px;
        color: #333333;
        text-align: center;
        font-weight: bold;
      }
    }

    .wjmm {
      text-align: right;
      font-size: 14px;
      font-family: SourceHanSansSC;
      font-weight: 400;
      color: #999999;
      cursor: pointer;
      margin-top: -10px;
      &:hover {
        color: #658fff;
      }
    }

    .anniu {
      @include twoAlign(320, 40);
      background: #658fff;
      border-radius: 4px;
      font-size: 16px;
      font-family: SourceHanSansSC;
      font-weight: 400;
      color: #ffffff;
      cursor: pointer;
      margin-top: 24px;
      margin-bottom: 12px;
    }

    .other {
      text-align: center;
      font-size: 14px;
      font-family: SourceHanSansSC;
      font-weight: 400;
      color: #658fff;
      cursor: pointer;
    }

    .xieyi {
      text-align: center;
      font-size: 14px;
      font-family: SourceHanSansSC;
      font-weight: 400;
      color: #999999;
      .gen {
        color: #658fff;
        cursor: pointer;
      }
    }

    .captcha {
      img {
        height: 32px;
        width: 90px;
        cursor: pointer;
        vertical-align: middle;
      }
    }

    .daojishi {
      font-size: 16px;
      color: #658fff;
    }

    .huoqu {
      font-size: 14px;
      font-family: Source Han Sans SC;
      font-weight: 400;
      color: #658fff;
      cursor: pointer;
    }
  }
}

.copyright {
  width: 100%;
  position: absolute;
  bottom: 0px;
  font-size: 12px;
  text-align: center;
  color: #333;
  z-index: 1000;
}
</style>
